package com.pro01.tracker.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.List;

public class PeerEncoder {

    public static byte[] compactPeers(List<PeerInfo> peers) {
        ByteBuffer buffer = ByteBuffer.allocate(peers.size() * 6);
        for (PeerInfo peer : peers) {
            try {
                byte[] ipBytes = InetAddress.getByName(peer.getIp()).getAddress(); // IPv4 only
                buffer.put(ipBytes);
                buffer.putShort((short) peer.getPort());
            } catch (UnknownHostException e) {
                // 忽略非法 IP
                continue;
            }
        }
        return buffer.array();
    }

    public static class PeerInfo {
        private final String ip;
        private final int port;

        public PeerInfo(String ip, int port) {
            this.ip = ip;
            this.port = port;
        }

        public String getIp() {
            return ip;
        }

        public int getPort() {
            return port;
        }
    }
}
